package t4dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import t4jdbc.JDBCUtil;
import t4bean.FruitBean;

public class FruitDao extends Dao {
	private SetSql ss = new SetSql();

	public int insert(FruitBean fruit) {
		String sql = "insert into fruit(name,cost,price,number) values(?,?,?,?)";
		List<Object> list = new ArrayList<>();
		list.add(fruit.getName());
		list.add(fruit.getCost());
		list.add(fruit.getPrice());
		list.add(fruit.getNumber());
		int n = 0;
		try {
			n = dml(sql, list);
			return n;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;

	}

	public int update(FruitBean fruit) {
		String sql = "update fruit set ";
		List<Object> list = new ArrayList<>();
		sql = ss.setSql(fruit, sql, list, 1);
		sql += " where name = ?";
		list.add(fruit.getName());

//		System.out.println(sql);
		try {
			return dml(sql, list);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public List<FruitBean> select(FruitBean fruit) throws SQLException {
		String sql;
		List<Object> list = new ArrayList<>();
		List<FruitBean> backList = new ArrayList<>();
		if (fruit != null) {
			sql = "select * from fruit where ";
			sql = ss.setSql(fruit, sql, list, 2);
		} else {
			sql = "select * from fruit";
		}
//		System.out.println(sql);
		ResultSet rs = null;
		try {
			rs = dql(sql, list);
			while (rs.next()) {
				FruitBean fruit1 = new FruitBean();
				fruit1.setName(rs.getString("name"));
				fruit1.setCost(rs.getInt("cost"));
				fruit1.setPrice(rs.getInt("price"));
				fruit1.setNumber(rs.getInt("number"));
				backList.add(fruit1);
			}
			return backList;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(super.conn, super.ps, super.rs);
			super.conn = null;
			super.ps = null;
			super.rs = null;
			rs.close();
			rs = null;
		}
		return null;
	}
}
